import axios from "axios";
// 类型转换
import qs from 'querystring'
// 创建axios对象
const instance = axios.create({
    timeout: 5000
})
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
// 处理状态码
const errorHandler = (status, other) => {
    switch (status) {
        case 400:
            console.log('请求语法有问题')
            break
        case 401:
            console.log('客户端未授权')
            break
        case 403:
            console.log('请求权限被拒绝')
            break
        case 404:
            console.log('URL地址无效')
            break
        default:
            console.log(other)
            break
    }
}
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

// 请求拦截器
instance.interceptors.request.use(config => {
        if (config.method === 'post') {
            config.data = qs.stringify(config.data)
        }
        //  判断token是否存在
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.authorization = token
        }
        // Nprogress.start()
        return config
    },
    error => Promise.reject(error))
// 响应拦截器
instance.interceptors.response.use(

    /*1.网络引起的失败 2.返回的数据失败*/
    response => response.status === 200 ? Promise.resolve(response) : Promise.reject(response),
    error => {
        const {response} = error
        if (response) {
            errorHandler(response.status, errorHandler.data)
            return Promise.reject(response)
        } else {
            console.log('网络请求被终端')
        }
    })
export default instance

